#!/bin/sh
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
# Gets yum data and displays the name, version & build-id
# build-id could be one of:
# build number - if the package was installed from an ISO
# repo name - if the package was installed/updated from an RPM repository
# RPM name - if the package was intalled locally (rpm install or yum localinstall)
# Example output
# contrail-analytics                     1-1304082216        148                 
# openstack-dashboard.noarch             2012.1.3-1.fc17     updates             
# contrail-agent                         1-1304091654        contrail-agent-1-1304091654.x86_64

TMPFILE=/tmp/yl.${BASHPID}
CONTRAILRPMS=/etc/contrail/rpm_list.txt
VERSIONFILE=/opt/contrail/contrail_packages/VERSION
CONTRAIL_INSTALLS="@contrail_install_repo"

# Installs variable - BUILDID in the env
if [ -f $VERSIONFILE ];
then
    source $VERSIONFILE
fi

/bin/rm -f $TMPFILE
/usr/bin/yum list installed > $TMPFILE

echo "Package                                Version                        Build-ID | Repo | RPM Name"
echo "-------------------------------------- ------------------------------ ----------------------------------"
if [  "$#" -ne 0 ]; then
    pkg_list=$*
else
    pkg_list=`cat $CONTRAILRPMS`
fi

for i in $pkg_list; do
  #j=$i; v="N/A"; r="N/A"
  j=""; v="", r=""
  #read j v r <<< `grep "^$i\." $TMPFILE`
  read j v r <<< `grep -Pzo "^$i\.[^\s]+[\s|\n]+[^\s]+[\s|\n]+[^\s]+" $TMPFILE | tr "\n" " "`
  rr=`echo $r|cut -f2 -d/`

  # Override if @contrail_install_repo
  if [ "$rr" == "$CONTRAIL_INSTALLS" ] && [[ -n $BUILDID ]]; then
      rr=$BUILDID
  fi

  # Only Installed packages are displayed
  if [[ -n $rr ]]; then
      printf "%-39s%-31s%-20s\n" $i $v $rr
  fi
done

/bin/rm -f $TMPFILE
